<%@ page language="java" contentType="text/xml; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*, java.net.*, java.io.*, javax.xml.parsers.*, javax.xml.transform.*, javax.xml.transform.dom.*, javax.xml.transform.stream.* , org.xml.sax.*, org.json.simple.*, org.json.simple.parser.*, org.w3c.dom.*, org.apache.commons.lang.StringEscapeUtils "%>
<%!    	 
	  /**
	 * This jsp should receive a GET request with a layer id and return xml metadata from solr
	 * @author Chris Barnett
	 */

	/**
	 * send query to Solr and return results, based on Steve's code in Searcher.java
	 * @param layerIds
	 * @return layerInfoMap
	 */
	private static Map<String, Map<String, String>> getDownloadInfoFromSolr(String[] layerIds)
	throws IOException, ParseException
	{
		//String serverName = "localhost";
		String serverName = "geoportal-demo.atech.tufts.edu";
	 	String port = "80";
	 	String layerIdsString = "";
	 	int j = layerIds.length;
		for(int i = 0; i < j - 1; i++){
			layerIdsString += "LayerId:" + layerIds[i] + "+OR+";
		}
		layerIdsString += "LayerId:" + layerIds[j - 1];
		String returnedColumns = "LayerId,FgdcText,Name";
		String solrQuery = "q=" + layerIdsString + "&fl=" + returnedColumns;
	 	String url$ = "http://" + serverName + ":" + port + "/solr/select/?" + solrQuery 
	 				  + "&wt=json";
	 	
		URL url = new URL(url$);
		InputStream inputStream = url.openStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String currentLine = bufferedReader.readLine();
		String resultRow = "";
		while (currentLine != null)
			{
				//currentLine = currentLine.replaceAll("\\n|\\r", " ");
				resultRow += currentLine;	
				currentLine = bufferedReader.readLine();
			}
		//use simple json to parse the results and place into a hashmap 
		JSONParser parser = new JSONParser();
  		JSONObject jsonObj = (JSONObject) parser.parse(resultRow);
		JSONObject jsonResponse = (JSONObject) jsonObj.get("response");
		String numFoundString = jsonResponse.get("numFound").toString();
		int numFound = Integer.parseInt(numFoundString);
		JSONArray docs = (JSONArray) jsonResponse.get("docs");

		Map<String,Map<String,String>> layerInfoMap = new HashMap<String, Map<String, String>>();
		for(int i = 0; i < numFound; i++){
			JSONObject currentResult = (JSONObject) docs.get(i);
			JSONArray currentKeyArray = (JSONArray) currentResult.get("LayerId");
			String currentKey = currentKeyArray.get(0).toString();
			Map<String,String> innerLayerInfoMap = new HashMap<String,String>();
			//this works, despite warnings
			innerLayerInfoMap = (Map <String, String>) currentResult;
			//temporary...EPSG code handling should occur elsewhere
			layerInfoMap.put(currentKey, innerLayerInfoMap);
		}
		//System.out.println(layerInfoMap.toString());
		return layerInfoMap;
	} 

	 private String getXmlFromString(String xmlString)
	 throws ParserConfigurationException, IOException, SAXException, TransformerException
	 {
		//parse the returned XML to make sure it is well-formed & to format
		//filter extra spaces from xmlString
		xmlString = xmlString.replaceAll(">[ \t\n\r\f]+<", "><");
		xmlString = xmlString.replaceAll("[\t\n\r\f]+", "");

		// Create a factory
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// Use document builder factory
		DocumentBuilder builder = factory.newDocumentBuilder();
		//Parse the document
		InputStream xmlInputStream = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
		Document document = builder.parse(xmlInputStream);

		Source xmlSource = new DOMSource(document);
		StringWriter stringWriter = new StringWriter();
		StreamResult streamResult = new StreamResult(stringWriter);
		
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

		transformer.transform(xmlSource, streamResult);
		String outputString = stringWriter.toString();

		return outputString;
	 }
%>

<%
	String layerId = request.getParameter("layer");
	String download = request.getParameter("download");

	
	if ((download == null)||(download.equals(false))){
   		download = "inline";
   } else {
	   download = "attachment";
   }
	try {
		//return a hashmap of hashmaps
		String[] arrLayerId = { layerId };
		Map <String, Map <String, String>> layerInfo = getDownloadInfoFromSolr(arrLayerId);
		String fgdcText = layerInfo.get(layerId).get("FgdcText");
		String fileName = layerInfo.get(layerId).get("Name").trim();
		fileName = fileName.replace(".", "_");
		fileName += ".xml";

		String filteredXmlString = getXmlFromString(fgdcText);

		response.setContentLength(filteredXmlString.getBytes("UTF-8").length);
		response.setHeader("Content-Disposition", download + "; filename=\"" + fileName + "\"");
		
		Writer outputWriter = response.getWriter();
		outputWriter.write(filteredXmlString);
		    
	} catch(Exception e) {
		response.setStatus(500);
		e.printStackTrace();
	}	 
	 
%>
